package cz.semjobKB.triples.stat;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import cz.semjobKB.conllx.api.ISentence;
import cz.semjobKB.conllx.api.IWord;

public class FrazesStats {
	
	HashMap<String, Integer> mergeConstituent = new HashMap<String, Integer>();
	
	HashMap<String, Integer> mergeMorpho = new HashMap<String, Integer>();
	
	public String processFrazes(List<ISentence> sentences) {
		String result = "";
		for (ISentence sentence : sentences) {
			for (IWord word : sentence.getWords()) {
				if (mergeConstituent.containsKey(word.getConstituent().toString())) {
					mergeConstituent.put(word.getConstituent().toString(), mergeConstituent.get(word.getConstituent().toString()) + 1);
				} else {
					mergeConstituent.put(word.getConstituent().toString(), 1);
				}
			}
		}		
		mergeConstituent = sortByValue(mergeConstituent);
		
		for (Entry<String, Integer> entry : mergeConstituent.entrySet()) {
			result += entry.getKey()+ "\t" + entry.getValue().toString() + "\n";
		}
		result += "\n\n\n";
		
		for (ISentence sentence : sentences) {
			for (IWord word : sentence.getWords()) {
				String morphoTag = word.getConstituent().toString() + " " + word.getWordType().toString() + " " + word.getGenus()+ " " + word.getNumber()+ " " + word.getFall()+ " " + word.getPerson();
				if (mergeMorpho.containsKey(morphoTag)) {
					mergeMorpho.put(morphoTag, mergeMorpho.get(morphoTag) + 1);
				} else {
					mergeMorpho.put(morphoTag, 1);
				}
			}
		}		
		mergeMorpho = sortByValue(mergeMorpho);
		
		for (Entry<String, Integer> entry : mergeMorpho.entrySet()) {
			result += entry.getKey()+ "\t" + entry.getValue().toString() + "\n";
		}
		
		return result;
		
	}
	
	public static <K, V extends Comparable<? super V>> HashMap<K, V> sortByValue(Map<K, V> map) 
	{
	    @SuppressWarnings("unchecked")
	    Map.Entry<K,V>[] array = map.entrySet().toArray(new Map.Entry[map.size()]);

	    Arrays.sort(array, new Comparator<Map.Entry<K, V>>() 
	    {
	        public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) 
	        {
	            return e2.getValue().compareTo(e1.getValue());
	        }
	    });

	    HashMap<K, V> result = new LinkedHashMap<K, V>();
	    for (Map.Entry<K, V> entry : array)
	        result.put(entry.getKey(), entry.getValue());

	    return result;
	}
}
